import axios from 'mhyaxios2'
import qs from 'qs'
import AES from "@/tools/aes";
import {
	createUuid
} from '@/util/common'

// 全局加载遮罩
import {
	Loading,
	Message
} from 'element-ui'
import md5 from 'js-md5'
let loading = {}
// 不加载loading白名单
const whitelist = [
	// 搜索商品
	'/api/search/itemSearch',
	// 顶部导航栏
	'/api/sysNavigation/queryNavigation',
	// 导航下拉菜单s
	'/api/nav/queryOfficeSupplies',
	'/api/nav/officeSuppliesinitchild',
	// 验证码
	'/api/login/verification',
	'/api/notice/mobileverifycode',
	// 购物车数量
	'/api/orderShoppingCart/ ',
	// 收藏
	'/api/myCollect/queryMyCollectByGoodId',
	// 收藏，取消收藏
	'/api/myCollect/saveOrUpdateMyCollect',
	// 白名单token
	'/api/blacklist/token/',
	// 组织树
	'/vapi/order/getOrgLazyTree',
	// 组织树
	'/vapi/order/getOrgLazyTree2',
	// 一级目录
	'/vapi/index/nav/queryOfficeSupplies',
	// 二级目录
	'/vapi/index/nav/officeSuppliesinitchild',
]
// 导入错误代码
import errorCode from './errorCode'

// 导入工具函数
import tools from '@/tools'

// 导入路由
import router from '@/router'
import {
	log
} from 'mathjs'

/**
 * @functionName HttpRequest
 * @param {String} baseUrl 基础请求地址
 * @return {Object} 返回请求结果
 * @description axios封装
 * @author 张航
 * @date 2020-03-19 11:49:21
 * @version V1.0.0
 */
class HttpRequest {
	constructor(baseUrl = '') {
		this.baseUrl = baseUrl
		this.queue = {}
		this.counter = 0;
	}

	getInsideConfig(Uuid) {
		const token = tools.localRead('access_token')
		const client_code = tools.localRead('client_code')
		let config = {
			baseURL: this.baseUrl,
			headers: {
				'Content-Type': 'application/json',
				// 'Authorization': tools.localRead('access_token'),
				'Metis-InternalModule': 'aaaa',
				'Metis-ReqId': Uuid ? Uuid : createUuid(),
				'Metis-Tenant': '8dd10f97bc684b4fbc845c0b344883aa',
				'Metis-UserId': tools.localRead('userId'),
				'Ag-UserId': tools.localRead('userId')

			},
			withCredentials: true,
			timeout: 60 * 1000 * 5,
			// cancelToken: new axios.CancelToken(function (cancel) {
			//   console.log(cancel)
			//   Message({
			//     message: cancel,
			//     type: 'warning'
			//   })
			//   loading.close()
			// })
		}
		// if (token) {
		//   config.headers['Authorization'] = token
		// }
		if (client_code) {
			config.headers['client_code'] = client_code
		}
		return config
	}
	destroy(url) {
		delete this.queue[url]
		let arr = Object.keys(this.queue);
		if (arr.length === 0) {
			loading.close()
		}
	}
	interceptors(instance, url) {
		// 请求拦截
		instance.interceptors.request.use(
			config => {
				this.queue[url] = true
				return config
			},
			error => {
				return Promise.reject(error)
			}
		)
		// 响应拦截
		instance.interceptors.response.use(
			res => {

				var server = res.headers.server;
				console.log(server)
				if (server != 'dmz') {
					localStorage.setItem("env", "内网")
				} else {
					localStorage.setItem("env", "外网")
				}
				this.destroy(url)
				var {
					data
				} = res
				if (data.code && data.code !== 0 && data.code !== 200) {
					Message.closeAll()
					Message({
						message: data.msg,
						type: 'warning'
					})
				}

				switch (data.code) {
					case 403:
						this.refreshReq();
						break;
					case 401:
						Message.closeAll()
						Message({
							message: data.msg,
							type: 'warning'
						})
						break;
				}
				// if (data.resultCode === 50001) {
				//   localStorage.clear()
				//   router.replace({
				//     name: 'login'
				//   })
				// }

				var jsonStr = JSON.stringify(data);
				var mathStr = jsonStr.match(/\$YC2K.*?\"/g);
				if (mathStr) {
					for (var i = 0; i < mathStr.length; i++) {
						var item = mathStr[i].substr(0, mathStr[i].length - 1).replace("$YC2K", "")
						if (item) {
							var keys = res.headers.keys;
							// console.log("AES解密 ： " + AES.decrypt(item, keys));
							var baba = AES.decrypt(item, keys);
							jsonStr = jsonStr.replace(mathStr[i], baba + '"');
						}
					}
					// console.log("解密后的json" + jsonStr);
					data = JSON.parse(jsonStr);
				}


				if (data && data.data === undefined) {
					return data;
				} else if (data.data == null && data.rows) {
					return data;
				} else {
					return data.data;
				}
			},
			error => {
				const {
					status = 'default', data = {}
				} = error.response
				switch (status) {
					case 403:
						Message.closeAll()
						Message({
							message: data.msg,
							type: 'warning'
						})
						this.refreshReq()
						break
					case 401:
						Message.closeAll()
						Message({
							message: data.msg,
							type: 'warning'
						})
						break
					case 404:
						// Message({
						//   message: '暂无数据',
						//   type: 'warong'
						// })
						// if (url.indexOf("role") > -1 || url.indexOf("user") > -1 || url.indexOf("org") > -1 ||
						// 	url.indexOf("resource") > -1) {
						// 	Message({
						// 		message: "请在内网环境下访问",
						// 		type: 'warning'
						// 	})
						// }
						break
					case 400:
						Message.closeAll()
						Message({
							message: data.msg,
							type: 'warning'
						})
						// 登录30分钟无操作，自动退出，跳转到登录页
						if (data.code === -5) {
							const token = tools.localRead('user_token')
							this.post(`/api/blacklist/token/${token}`).then(() => {
								this.goToLogin()
							})
						}
						break
					case 500:
						Message.closeAll()
						Message({
							message: data.msg,
							type: 'warning'
						})
						if (data.msg == "您的账号已在其他设备登录，请重新登录！") {
							localStorage.clear()
							router.replace({
								name: 'login'
							})
						}
						break
					default:
						//   localStorage.clear()
						// router.replace({
						//   name: 'login'
						// })
						break;
				}

				this.destroy(url)
				// tools.addErrorLog(_error)
				return Promise.reject(error.response.data)
			}
		)
	}
	request(options, Uuid) {
		let showLoading = true
		whitelist.forEach(item => {
			if (options.url.indexOf(item) >= 0) {
				showLoading = false
			}
		})
		if (showLoading) {
			loading = Loading.service({
				lock: true,
				text: '正在加载……'
			})
		} else {
			if (!loading.close) {
				loading.close = () => {}
			}
		}
		const instance = axios.create()
			options.client = 'pc';
		options = Object.assign(this.getInsideConfig(Uuid), options)
		var data = options.data;
		var params = options.params;

		var timestamp = Date.parse(new Date()) / 1000;
		if (data == null) {
			data = {}
		}
		// 签名时需要对data中的数据进行一次排序
		var uuid = createUuid();
		var qiantai = localStorage.getItem("qiantai") ? localStorage.getItem("qiantai") : '';
		var newStr = uuid + timestamp + qiantai;
		const sign = md5(newStr);
		options.headers['sign'] = sign;
		options.headers['uuid'] = uuid;
		options.headers['timestamp'] = timestamp;
		const token = tools.localRead('access_token')
		if (options.url) {
			if (options.url.indexOf("vapi") > -1 || options.url.indexOf("liser") > -1 || options.url.indexOf(
					"mhy") > -1 || options.url.indexOf("dongbo") > -1 || options.url.indexOf("chart") > -1 ||
				options.url.indexOf("work-order") > -1 ||
				options.url.indexOf("special") > -1) {
				if (qiantai) {
					options.headers['Authorization'] = qiantai
				}
			} else {
				if (token) {
					options.headers['Authorization'] = token
				}
			}
		}
		this.interceptors(instance, options.url)
		return instance(options)
	}
	/**
	 * @functionName get
	 * @param {String} url 请求地址
	 * @return {Object} 返回结果
	 * @description 查询
	 * @author 张航
	 * @date 2020-03-20 10:45:17
	 * @version V1.0.0
	 */
	get(url = '', params = {}, Uuid = '') {
		const config = {
			url,
			method: 'get',
			params
		}
		return this.request(config, Uuid)
	}
	/**
	 * @functionName post
	 * @param {String} url 请求地址
	 * @param {Object} data 请求数据
	 * @param {Boolean} url 请求类型: true: json; false:formdata;
	 * @param {String } Uuid 登录时验证码与用户绑定
	 * @return {Object} 返回结果
	 * @description 提交
	 * @author 张航
	 * @date 2020-03-20 10:45:17
	 * @version V1.0.0
	 */
	post(url = '', data = {}, type = true, Uuid = '') {
		const _data = type ? data : qs.stringify(data, {
			arrayFormat: 'repeat'
		})
		const config = {
			url,
			data: _data,
			method: 'post'
		}
		return this.request(config, Uuid)
	}
	/**
	 * @functionName put
	 * @param {String} url 请求地址
	 * @param {Object} data 请求数据
	 * @param {Boolean} url 请求类型: true: json; false:formdata;
	 * @return {Object} 返回结果
	 * @description 修改
	 * @author 张航
	 * @date 2020-03-20 10:45:17
	 * @version V1.0.0
	 */
	put(url = '', data = {}, type = true, Uuid = '') {
		const _data = type ? data : qs.stringify(data, {
			arrayFormat: 'repeat'
		})
		const config = {
			url,
			data: _data,
			method: 'put'
		}
		return this.request(config, Uuid)
	}
	/**
	 * @functionName delete
	 * @param {String} url 请求地址
	 * @param {Boolean} url 请求类型: true: json; false:formdata;
	 * @return {Object} 返回结果
	 * @description 删除
	 * @author 张航
	 * @date 2020-03-20 10:45:17
	 * @version V1.0.0
	 */
	delete(url = '', type = true) {
		const config = {
			url,
			method: 'delete'
		}
		return this.request(config)
	}
	/**
	 * @functionName patch
	 * @param {String} url 请求地址
	 * @param {Object} data 请求数据
	 * @param {Boolean} url 请求类型: true: json; false:formdata;
	 * @return {Object} 返回结果
	 * @description 部分修改
	 * @author 张航
	 * @date 2020-09-16 16:32:51
	 * @version V1.0.0
	 */
	patch(url = '', data = {}, type = true) {
		const _data = type ? data : qs.stringify(data, {
			arrayFormat: 'repeat'
		})
		const config = {
			url,
			data: _data,
			method: 'patch'
		}
		return this.request(config)
	}

	/**
	 * @functionName get
	 * @param {String} url 请求地址
	 * @return {Object} 返回结果
	 * @description 查询
	 * @author 张航
	 * @date 2020-03-20 10:45:17
	 * @version V1.0.0
	 */
	download(url, params = {}) {
		const config = {
			url,
			method: 'get',
			'responseType': 'blob',
			params
		}
		return this.request(config)
	}

	postDownload(url, data = {}) {
		const config = {
			url,
			method: 'post',
			'responseType': 'blob',
			data
		}
		return this.request(config)
	}


	// 刷新toekn
	refreshReq() {
		this.goToLogin();
		// tools.localSave('access_token', '')
		// const refreshToken = tools.localRead('refresh_token')
		// const username = tools.localRead('user_name')
		// this.post('/api/login/refresh', { refreshToken, username }).then(res => {

		//   let tokenType = res.token_type
		//   tokenType = tokenType.charAt(0).toUpperCase() + tokenType.slice(1)

		//   tools.localSave('access_token', tokenType + ' ' + res.access_token)
		//   tools.localSave('refresh_token', res.refresh_token)
		//   window.location.href = window.location.href
		// }).catch(err => {
		//   this.goToLogin()
		// })

	}
	// 跳转到登录页
	goToLogin() {
		localStorage.clear()
		var url = window.location;
		if (url.hostname.indexOf('10.151.38.185') > -1 || url.hostname.indexOf('www.ansteelmro.com') > -1 || url
			.hostname.indexOf('run.ansteelmro.com') > -1) {
			window.location.href = url.origin + '/login'
		} else {
			router.replace({
				name: 'login'
			})
		}
	}
}

export default HttpRequest